import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect

from pacp.lib.base import BaseController, render
from pacp import model
from pylons.decorators import jsonify
from pacp.lib.pql import Pql

from pacp.model import run_flds
from pacp.lib.pipetech import RUNS
import types

log = logging.getLogger(__name__)





class QueryController(BaseController):
    @jsonify
    def run(self):
        # Return a rendered template
        #return render('/query.mako')
        # or, return a response
        try:
            #the pql
            q = request.params['query']
        except:
            q = None
        try:
            limit = int(request.params['limit'])
        except:
            limit = 25
        try:
            start = int(request.params['start'])
        except:
            start = 0

#        try:
        if q:
            sql = Pql(q).SQL
            q = model.meta.Session.query(model.Run).from_statement(sql).all()
            ct = len(q)
        else:
            q = model.meta.Session.query(model.Run)
            ct = q.count()
       
        result = []
        for r in q[start:start +limit]:
            record = {}
            for fld in run_flds:
                #Float formating
                if RUNS[fld][0]=='Float':
                    if getattr(r, fld):
                        record[fld] = '%.2f' % getattr(r, fld)
                    else:
                        record[fld] = None
                else:
                    record[fld] = getattr(r, fld)
            #EXT template doesn't support Height_(Diameter), so I have to create a new one
            record['dia'] = getattr(r, 'Height_(Diameter)')
            result.append(record)
        return {'totalcount': ct, 'runs': result,  'success': True}#        except:
#            return {'success': False}

    @jsonify
    def validate(self):
        try:
            #the pql
            q = request.params['q']
        except:
            q = None
        if q:
            query = Pql(q)
            return {'success': query.valid, 'reason': 'success', 'results': query.results}
        
        
